const { Controller } = require("egg");
const path = require("path");
const fs = require("fs");
const { respAdapter } = require("../../utils");
const xlsx = require("node-xlsx");
class ManagerController extends Controller {
  async list() {
    const { ctx, app, config } = this;
    try {
      const token = ctx.headers.authorization
        ? ctx.headers.authorization.split(" ")[1]
        : "";
      await app.jwt.verify(token, config.jwt.secret);

      const query = ctx.query;
      let params = [];

      let sqlQuery = "SELECT * FROM manager";
      console.log("😈query", query);

      for (const [key, value] of Object.entries(query)) {
        if (value) {
          if (sqlQuery.indexOf("WHERE") == -1) {
            sqlQuery += " WHERE";
            params.push(`%${value}%`);
          }
          // 确保只有当搜索字符串不为空时才添加条件
          sqlQuery += ` ${key} LIKE ? `;
        }
      }

      sqlQuery = sqlQuery.replace(/ AND $/, "");
      sqlQuery += "  ORDER BY created_time DESC";
      console.log("sqlQuery", sqlQuery);

      const list = await this.app.mysql.query(sqlQuery, params);

      if (!list) {
        ctx.body = respAdapter(null, "数据异常，请重试", false);
      }

      ctx.body = respAdapter({ list });
    } catch (err) {
      console.log("😈err", err);
      ctx.body = respAdapter(null, err, false);
    }
  }

  async detail() {
    const { ctx, app, config } = this;
    try {
      const token = ctx.headers.authorization
        ? ctx.headers.authorization.split(" ")[1]
        : "";
      await app.jwt.verify(token, config.jwt.secret);

      const query = ctx.query;
      const data = await this.app.mysql.get("manager", query);

      if (!data) {
        ctx.body = respAdapter(null, "数据异常，请重试", false);
      }

      ctx.body = respAdapter({
        ...data
      });
    } catch (err) {
      ctx.body = respAdapter(null, err, false);
    }
  }

  async create() {
    const { ctx, app, config } = this;
    const { body } = ctx.request;
    try {
      const token = ctx.headers.authorization
        ? ctx.headers.authorization.split(" ")[1]
        : "";
      await app.jwt.verify(token, config.jwt.secret);

      const resp = await this.app.mysql.insert("manager", {
        ...body,
        created_time: new Date()
      });
      ctx.body = respAdapter({}, null, !!resp);
    } catch (err) {
      ctx.body = respAdapter(null, err, false);
    }
  }

  async import() {
    const { ctx, app, config } = this;
    const { body } = ctx.request;
    try {
      const files = ctx.request.files; // 获取上传的文件列表
      const file = files?.[0];

      // 使用 node-xlsx 解析 Excel 文件
      const workSheets = xlsx.parse(file?.filepath, {
        cellDates: true, // 这个选项告诉node-xlsx将日期的序列号转换为Date对象
        defaultCellType: "string" // 将所有单元格默认类型设置为字符串，防止日期被转换为数字
      });

      // 这里假设我们只处理第一个工作表
      const data = workSheets[0].data;

      // 处理数据...
      console.log(data);
      const insertList = [];
      data.forEach((item, index) => {
        if (index !== 0) {
          const [
            name,
            sex,
            birthday,
            area,
            score,
            project_company_name,
            project_name,
            company_name
          ] = item;
          insertList.push({
            name,
            sex,
            birthday,
            area: area.replace(/\//g, ","),
            score,
            project_company_name,
            project_name,
            company_name,
            created_time: new Date()
          });
        }
      });

      const result = await this.app.mysql.insert("manager", insertList);

      ctx.body = respAdapter({}, null, !!result);

      // const resp = await this.app.mysql.insert("manager", body);
      // ctx.body = respAdapter({}, null, !!resp);
    } catch (err) {
      console.log("[err]", err);
      ctx.body = respAdapter(null, err, false);
    }
  }

  async update() {
    const { ctx, app, config } = this;
    const { body } = ctx.request;
    try {
      const token = ctx.headers.authorization
        ? ctx.headers.authorization.split(" ")[1]
        : "";
      await app.jwt.verify(token, config.jwt.secret);

      const resp = await this.app.mysql.update("manager", body);
      ctx.body = respAdapter({}, null, !!resp);
    } catch (err) {
      ctx.body = respAdapter(null, err, false);
    }
  }

  async delete() {
    const { ctx, app, config } = this;
    const { body } = ctx.request;
    try {
      const token = ctx.headers.authorization
        ? ctx.headers.authorization.split(" ")[1]
        : "";
      await app.jwt.verify(token, config.jwt.secret);

      const resp = await this.app.mysql.delete("manager", body);
      ctx.body = respAdapter({}, null, !!resp);
    } catch (err) {
      ctx.body = respAdapter(null, err, false);
    }
  }
}

module.exports = ManagerController;
